#include "manager.h"
#include "machine.h"

#include <unistd.h>

namespace pinflow
{

bool Manager::Prepare(const Config& config)
{
    (void)config;
    return true;
}

bool Manager::Deploy()
{
    return true;
}

bool Manager::Loop(bool& flag)
{
    size_t mcount = machines_.size();
    bool ret = true;
    while(flag) {
        for (size_t i = 0; i < mcount; ++i) {
            if (!machines_[i]->IsRunning()) {
                continue;
            }
            std::string name = machines_[i]->Name();
            Config config = machines_[i]->ConfigItems();
            machines_[i] = CreateMachine(name, config);
            ret = machines_[i]->Init();
            if(ret != true) {
                flag = false;
                break;
            }
            ret = machines_[i]->Loop(queues_, flag);
            if (ret != true) {
                flag = false;
                break;
            }
        }

        // 每秒钟查询一下状态
        // 如果value值没有更新，那么认为线程状态异常
        usleep(1000000);
    }

    return true;
}

Machine::sptr Manager::CreateMachine(const std::string& name,
    const Config& config)
{
    auto sptr = Machine::Create();
    sptr->SetName(name);
    sptr->SetState(Machine::UNKNOWN);
    sptr->SetConfig(config);
    return sptr;
}


    
}